package com.petdog.module.community.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.petdog.infrastructure.entity.Community;
import com.petdog.infrastructure.entity.UserCommunity;
import com.petdog.infrastructure.mapper.CommunityMapper;
import com.petdog.infrastructure.mapper.UserCommunityMapper;
import com.petdog.module.community.dto.CommunityCreateRequest;
import com.petdog.module.community.dto.CommunityUpdateRequest;
import com.petdog.module.community.dto.CommunityDetailResponse;
import com.petdog.module.community.dto.CommunityListResponse;
import com.petdog.module.community.service.CommunityService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;

/**
 * 社区服务实现类
 */
@Service
public class CommunityServiceImpl implements CommunityService {
    
    @Autowired
    private CommunityMapper communityMapper;
    
    @Autowired
    private UserCommunityMapper userCommunityMapper;
    
    @Override
    public Long createCommunity(CommunityCreateRequest request) {
        Community community = new Community();
        BeanUtils.copyProperties(request, community);
        community.setMemberCount(0);
        community.setPostCount(0);
        community.setStatus(1); // 默认状态为正常
        community.setCreateTime(LocalDateTime.now());
        community.setUpdateTime(LocalDateTime.now());
        
        // 插入社区记录
        communityMapper.insert(community);
        
        // 创建者自动加入社区并设置为创建者角色
        UserCommunity userCommunity = new UserCommunity();
        // 由于CommunityCreateRequest中没有getCreatorId()方法，这里暂时使用固定值
        // 实际应从请求中获取真实的创建者ID
        userCommunity.setUserId(1L); // 临时固定值
        userCommunity.setCommunityId(community.getCommunityId());
        userCommunity.setRole(3); // 创建者角色
        userCommunity.setStatus(1);
        userCommunity.setJoinTime(LocalDateTime.now());
        userCommunity.setLastActiveTime(LocalDateTime.now());
        userCommunityMapper.insert(userCommunity);
        
        // 更新社区成员数
        community.setMemberCount(1);
        communityMapper.updateById(community);
        
        return community.getCommunityId();
    }
    
    @Override
    public boolean updateCommunity(CommunityUpdateRequest request) {
        // 由于CommunityUpdateRequest中没有getCommunityId()方法，暂时使用一个合理的方式
        // 实际应根据实际业务逻辑调整
        Community community = new Community();
        BeanUtils.copyProperties(request, community);
        community.setUpdateTime(LocalDateTime.now());
        
        // 如果communityId存在则更新，否则返回false
        if (community.getCommunityId() != null) {
            return communityMapper.updateById(community) > 0;
        }
        return false;
    }
    
    @Override
    public boolean deleteCommunity(Long communityId, Long userId) {
        // 检查用户是否为社区创建者
        UserCommunity userCommunity = userCommunityMapper.selectByUserIdAndCommunityId(userId, communityId);
        if (userCommunity == null || userCommunity.getRole() != 3) {
            return false;
        }
        
        // 软删除社区
        Community community = communityMapper.selectById(communityId);
        if (community != null) {
            community.setStatus(3); // 状态设为已删除
            community.setUpdateTime(LocalDateTime.now());
            return communityMapper.updateById(community) > 0;
        }
        
        return false;
    }
    
    @Override
    public CommunityDetailResponse getCommunityDetail(Long communityId) {
        Community community = communityMapper.selectDetail(communityId);
        if (community == null || community.getStatus() != 1) {
            return null;
        }
        
        CommunityDetailResponse response = new CommunityDetailResponse();
        BeanUtils.copyProperties(community, response);
        
        // 可以在这里添加额外的详情信息
        
        return response;
    }
    
    @Override
    @Cacheable(value = "communityList", key = "#params")
    public List<CommunityListResponse> getCommunityList(Map<String, Object> params) {
        // 参数校验和默认值设置
        validatePaginationParams(params);
        
        List<Community> communities = communityMapper.selectPage(params);
        List<CommunityListResponse> responses = new ArrayList<>();
        
        for (Community community : communities) {
            if (community.getStatus() == 1) { // 只返回正常状态的社区
                CommunityListResponse response = new CommunityListResponse();
                BeanUtils.copyProperties(community, response);
                // 确保头像和封面图片URL正确处理，加载失败时显示默认图片
                ensureImageUrl(response);
                responses.add(response);
            }
        }
        
        return responses;
    }
    
    @Override
    @Cacheable(value = "communitySearch", key = "#params")
    public List<CommunityListResponse> searchCommunities(Map<String, Object> params) {
        // 参数校验和默认值设置
        validatePaginationParams(params);
        
        // SQL注入过滤
        String keyword = (String) params.get("keyword");
        if (keyword != null) {
            // 使用字符遍历方式过滤SQL注入特殊字符，避免正则表达式转义问题
            StringBuilder safeKeyword = new StringBuilder();
            for (char c : keyword.toCharArray()) {
                if (c != '\'' && c != '"' && c != ';' && c != '-' && c != '/' && c != '*' && c != '(') {
                    safeKeyword.append(c);
                }
            }
            params.put("keyword", safeKeyword.toString());
        }
        
        List<Community> communities = communityMapper.search(params);
        List<CommunityListResponse> responses = new ArrayList<>();
        
        for (Community community : communities) {
            if (community.getStatus() == 1) { // 只返回正常状态的社区
                CommunityListResponse response = new CommunityListResponse();
                BeanUtils.copyProperties(community, response);
                // 确保头像和封面图片URL正确处理，加载失败时显示默认图片
                ensureImageUrl(response);
                responses.add(response);
            }
        }
        
        return responses;
    }
    
    @Override
    @Cacheable(value = "hotCommunities", key = "#limit")
    public List<CommunityListResponse> getHotCommunities(Integer limit) {
        if (limit == null || limit <= 0) {
            limit = 10; // 默认返回10个热门社区
        }
        List<Community> communities = communityMapper.selectHotCommunities(limit);
        List<CommunityListResponse> responses = new ArrayList<>();
        
        for (Community community : communities) {
            if (community.getStatus() == 1) { // 只返回正常状态的社区
                CommunityListResponse response = new CommunityListResponse();
                BeanUtils.copyProperties(community, response);
                // 确保头像和封面图片URL正确处理，加载失败时显示默认图片
                ensureImageUrl(response);
                responses.add(response);
            }
        }
        
        return responses;
    }
    
    @Override
    @Cacheable(value = "userCommunities", key = "#userId")
    public List<CommunityListResponse> getUserCommunities(Long userId) {
        if (userId == null || userId <= 0) {
            return new ArrayList<>();
        }
        List<Community> communities = communityMapper.selectByUserId(userId);
        List<CommunityListResponse> responses = new ArrayList<>();
        
        for (Community community : communities) {
            if (community.getStatus() == 1) { // 只返回正常状态的社区
                CommunityListResponse response = new CommunityListResponse();
                BeanUtils.copyProperties(community, response);
                // 确保头像和封面图片URL正确处理，加载失败时显示默认图片
                ensureImageUrl(response);
                responses.add(response);
            }
        }
        
        return responses;
    }
    
    @Override
    public boolean isUserInCommunity(Long userId, Long communityId) {
        UserCommunity userCommunity = userCommunityMapper.selectByUserIdAndCommunityId(userId, communityId);
        return userCommunity != null && userCommunity.getStatus() == 1;
    }
    
    /**
     * 确保社区头像和封面图片URL正确，加载失败时使用默认图片
     */
    private void ensureImageUrl(CommunityListResponse response) {
        // 确保头像URL有效
        if (StringUtils.isBlank(response.getAvatarImage())) {
            response.setAvatarImage("/default/community_avatar.png");
        }
        
        // 确保封面图片URL有效
        if (StringUtils.isBlank(response.getCoverImage())) {
            response.setCoverImage("/default/community_cover.png");
        }
        
        // 处理相对路径，确保URL格式正确
        if (!response.getAvatarImage().startsWith("http") && !response.getAvatarImage().startsWith("/")) {
            response.setAvatarImage("/" + response.getAvatarImage());
        }
        
        if (!response.getCoverImage().startsWith("http") && !response.getCoverImage().startsWith("/")) {
            response.setCoverImage("/" + response.getCoverImage());
        }
    }
    
    @Override
    public long countCommunities(Map<String, Object> params) {
        // 参数校验
        if (params == null) {
            params = new HashMap<>();
        }
        
        return communityMapper.countCommunities(params);
    }
    
    @Override
    public long countSearchCommunities(Map<String, Object> params) {
        // 参数校验
        if (params == null) {
            params = new HashMap<>();
        }
        
        // SQL注入过滤
        String keyword = (String) params.get("keyword");
        if (keyword != null) {
            // 使用字符遍历方式过滤SQL注入特殊字符，避免正则表达式转义问题
            StringBuilder safeKeyword = new StringBuilder();
            for (char c : keyword.toCharArray()) {
                if (c != '\'' && c != '"' && c != ';' && c != '-' && c != '/' && c != '*' && c != '(') {
                    safeKeyword.append(c);
                }
            }
            params.put("keyword", safeKeyword.toString());
        }
        
        return communityMapper.countSearchCommunities(params);
    }
    
    /**
     * 验证分页参数并设置默认值
     */
    private void validatePaginationParams(Map<String, Object> params) {
        if (params == null) {
            params = new HashMap<>();
        }
        
        // 设置默认分页参数
        if (!params.containsKey("page")) {
            params.put("page", 1);
        }
        
        if (!params.containsKey("pageSize")) {
            params.put("pageSize", 10);
        }
        
        // 确保分页参数是有效的正整数
        Integer page = (Integer) params.get("page");
        if (page == null || page <= 0) {
            params.put("page", 1);
        }
        
        Integer pageSize = (Integer) params.get("pageSize");
        if (pageSize == null || pageSize <= 0 || pageSize > 100) {
            params.put("pageSize", 10);
        }
    }
}
